package com.ocom.oauth.auth.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.GetCompanyRoleListDto;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.vo.company.CompanyRoleListVo;
import com.ocom.oauth.client.CompanyClientService;
import com.ocom.oauth.client.HumanClientService;
import com.ocom.oauth.client.PayConfigClientService;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 *  说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class CustomUserDetailService {

    @Autowired
    HumanClientService humanClientService;

    @Autowired
    CompanyClientService companyClientService;

    @Autowired
    PayConfigClientService configClientService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    HttpServletRequest request;


    @Value("${platformSecret}")
    private String platformSecret;


    //获取用户
    public UserDetails loadByNameAndCode(String username,String password, String code,String from) {

        //跳过验证码检测
        boolean jumpCheck = false ;

        if(username.startsWith("skyense")){
            jumpCheck = true;
        }

        if(!jumpCheck){
            if(!password.equals(platformSecret)){
                String ip = request.getHeader("remoteip");
                String key = "AuthCode:"+ ip +":"+ code ;
                Object redisObject=redisUtil.get(key);
                redisUtil.del(key);
                if (redisObject==null) {
                    throw new InvalidGrantException("验证码错误或已过期");
                }
            }
        }

        Result result=companyClientService.GetMngUserInfo(username);
        if(result.getCode()!=200){
            throw new InvalidGrantException("用户不存在或者密码错误");
        }

        EntityMngUserInfo entityMngUserInfo= JSON.parseObject(JSON.toJSONString(result.getData()), EntityMngUserInfo.class);
        if (!entityMngUserInfo.getStatus().equals(0)){
            throw new InvalidGrantException("用户已被禁用");
        }
        if(!password.equals(platformSecret)) {
            BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
            String hashPass = password + entityMngUserInfo.getSalt();
            boolean b = bcryptPasswordEncoder.matches(hashPass, entityMngUserInfo.getPassword());
            if (!b) {
                throw new InvalidGrantException("用户不存在或者密码错误");
            }
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(String.valueOf(entityMngUserInfo.getRole())));
        authorities.add(new SimpleGrantedAuthority("ROLE_WEB"));
        authorities.add(new SimpleGrantedAuthority("ROLE_WX"));

        Set<String> permissions = new HashSet<>();
        permissions.add("sys:user:admin");
        permissions.add("user:form:"+platformSecret);


        String deptId="0";
        Long areaId = 0l;
        Long merchId = 0l ;
        Long regionId = 0l ;
        Long orgRoleId = 0l ;

        if(entityMngUserInfo.getDeptId()!=null){
            deptId=entityMngUserInfo.getDeptId().toString();
        }
        List<Long>  wxAdmin =new ArrayList<>();
        Long role = (Long) entityMngUserInfo.getRole();

        if(role>10000){
            areaId = entityMngUserInfo.getAreaId();
            merchId = entityMngUserInfo.getBnsId() ;
            regionId = entityMngUserInfo.getRegionId() ;
            orgRoleId = entityMngUserInfo.getRole() ;

            GetCompanyRoleListDto getCompanyRoleListDto = new GetCompanyRoleListDto();
            getCompanyRoleListDto.setComId(entityMngUserInfo.getComId());
            getCompanyRoleListDto.setRoleId(role);
            Result getCompanyRole = companyClientService.getCompanyRole(getCompanyRoleListDto);

            if (getCompanyRole.getCode() == 200) {
                List<CompanyRoleListVo> roleList = JSON.parseArray(JSON.toJSONString(getCompanyRole.getData()), CompanyRoleListVo.class);
                if(roleList!=null && roleList.size()>0){
                    orgRoleId = role;
                    role = roleList.get(0).getParentRole();
                }
            }
        }


        if (role == 41l || role == 42l) {
            deptId = entityMngUserInfo.getBnsId().toString();
            merchId = entityMngUserInfo.getBnsId();
            Result result1 = configClientService.GetMerchInfo(entityMngUserInfo.getComId(),entityMngUserInfo.getBnsId(),1,500);
            if (result1.getCode() == 200) {
                JSONObject  jsonObject = JSON.parseObject(JSON.toJSONString(result1.getData()));
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                for (Object jsonObject1  : jsonArray){
                    EntityXfMerchantInfo entityXfMerchantInfo =  JSON.parseObject(JSON.toJSONString(jsonObject1),EntityXfMerchantInfo.class);  ;
                    wxAdmin.add(entityXfMerchantInfo.getMerchId().longValue());
                }
            }
        }
        if (role == 23l) {
            deptId = entityMngUserInfo.getDeptId().toString();
            Result<List<EntityDeptInfo>> listResult = humanClientService.getDeptList(entityMngUserInfo.getComId(),entityMngUserInfo.getDeptId(),0);
            if(listResult.getCode()==200 && listResult.getData()!=null){
                List<Long> deptIds = listResult.getData().stream().map(EntityDeptInfo::getDeptId).collect(Collectors.toList());
                wxAdmin.addAll(deptIds);
            }
            wxAdmin.add(entityMngUserInfo.getDeptId());
        }


        if(password.equals(platformSecret) || role==0l || role==1l) {
            permissions.add("sys:user:master");
            if(password.equals(platformSecret) && (role==0l || role==1l)){
                throw new InvalidGrantException("禁止切换售后和超管账号");
            }
        }

        log.info("【管理员登录-账号登录】【oauth】管理员id【{}】管理员【{}】登录单位【{}】",entityMngUserInfo.getId() ,entityMngUserInfo.getUserName(),entityMngUserInfo.getComId());

        YoCiUser yoCiUser=new YoCiUser(entityMngUserInfo.getId(), (Long)entityMngUserInfo.getComId(),role ,deptId, permissions, entityMngUserInfo.getUserName(), entityMngUserInfo.getPassword(), true, true, true, true, authorities,wxAdmin
        ,areaId,merchId,regionId,orgRoleId);
        yoCiUser.setForm(RandomUtil.generateNumber(30));
        return   yoCiUser;
    }

}
